package com.example.baiduapi.Scoket.websocket.interceptor;

import com.alibaba.fastjson.JSON;
import com.example.baiduapi.Mapper.mysqlMapper.UserMapper;
import com.example.baiduapi.Scoket.websocket.constant.ConstantPool;
import com.example.baiduapi.Scoket.websocket.handler.MyWebSocketHandler;
import com.example.baiduapi.Util.EncPassword;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import javax.swing.*;
import java.awt.*;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class WebSocketInterceptor implements HandshakeInterceptor {
    private Logger logger = LoggerFactory.getLogger(WebSocketInterceptor.class);
    /**
     * @Description: Handler处理前调用
     * @Param: [serverHttpRequest, serverHttpResponse, webSocketHandler, map]
     * @return: boolean
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {


        if (serverHttpRequest instanceof ServletServerHttpRequest) {

            @SuppressWarnings("unused")
			ServletServerHttpRequest request = (ServletServerHttpRequest) serverHttpRequest;
            // 接收UUID
            String ids = request.getURI().getQuery();
            Map<String, String> idsMap = EncPassword.parseString(ids);
            System.out.println(idsMap);
            String uuid = idsMap.get("uuid");
            String sid = idsMap.get("SID");
            if (EncPassword.string2MD5(sid).equals(uuid)){
                map.put(ConstantPool.USER_UUID_KEY, sid);
                return true;
            } else {
                String[] split = uuid.split("￣￣");
                if (split[1].equals("验证码默认用户")){
                    map.put(ConstantPool.USER_UUID_KEY, sid);
                    return true;
                }
                logger.error("uuid和sid不正确,UUID{},SID{}",uuid,sid);
                return false;
            }
        } else {
            return false;
        }
    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {

    }
}
